//
//  SAPrintLableVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/6.
//

#import "SAPrintLableVC.h"
#import "SAPrintLableCell.h"
#import "SAProductBarcodeListAPI.h"
#import "SAPrintLableModel.h"
#import "ScanHelper.h"
#import "SAProductBarcodeSingleListAPI.h"
#import "SACommoditySpecialFeesModel.h"
#import "SACloudPrintPushPrintMsgAPI.h"
#import "CloudPrint.h"
#import "SASearchSupplierView.h"
#import "SASupplierModel.h"
#import "HDDatePickerView.h"
#import "NSDate+HMProjectKit.h"

@interface SAPrintLableVC ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topContentView;
@property (nonatomic, strong) UILabel *startLab;
@property (nonatomic, strong) UILabel *startDateLab;
@property (nonatomic, strong) UILabel *endLab;
@property (nonatomic, strong) UILabel *endDateLab;
@property (nonatomic, strong) UIImageView *iconImageV;
@property (nonatomic, strong) UIButton *startDateBtn;
@property (nonatomic, strong) UIButton *endDateBtn;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITextField *searchTf;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *goodsBarcodeBtn;
@property (nonatomic, strong) UIButton *singleBarcodeBtn;
@property (nonatomic, strong) UIButton *printBtn;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAProductBarcodeListAPI *productBarcodeListAPI;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSMutableArray<SAPrintLableModel *> *dataMarr;
@property (nonatomic, strong) NSMutableArray<SAPrintLableModel *> *selectMarr;
@property (nonatomic, strong) UIButton *allSelectBtn;
@property (nonatomic, strong) UILabel *selectLab;
@property (nonatomic, strong) UILabel *totalLab;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) SAProductBarcodeSingleListAPI *productBarcodeSingleListAPI;
@property (nonatomic, strong) SACloudPrintPushPrintMsgAPI *cloudPrintPushPrintMsgAPI;
@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, assign) BOOL isTip;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;
@property (nonatomic, strong) UIButton *vipBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSString *providerId;//供货商id

@end

@implementation SAPrintLableVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.productBarcodeListAPI == api || self.productBarcodeSingleListAPI == api) {
        if (self.currentPage == 1) {
            if (self.dataMarr.count > 0){
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
            }
            self.allSelectBtn.selected = NO;
            [self.selectMarr removeAllObjects];
            [self.dataMarr removeAllObjects];
            [self totalCount];
        }
        
        NSMutableArray *marr = [SAPrintLableModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        for (SAPrintLableModel *model in marr) {
            if ([model.stock doubleValue] > 0) {
                model.printNum = model.stock;
            }else {
                model.printNum = @"0";
            }
            [self.dataMarr addObject:model];
        }
        [self.tableView reloadData];
        self.tipView.hidden = (self.dataMarr.count > 0);
    }else if (self.cloudPrintPushPrintMsgAPI == api) {
        if (self.isTip == YES) {
            [Prompt popPromptViewWithMsg:@"正在进行共享打印" duration:2];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAPrintLableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAPrintLableCell"];
    SAPrintLableModel *mode = self.dataMarr[indexPath.section];
    if (self.goodsBarcodeBtn.selected == YES) {
        cell.model = mode;
    }else {
        cell.singleModel = mode;
    }
    __weak typeof(self) weakSelf = self;
    cell.selectBlock = ^{
        [weakSelf.view endEditing:YES];
        if (mode.isSelect == YES) {
            [weakSelf.selectMarr addObject:mode];
        }else {
            [weakSelf.selectMarr removeObject:mode];
        }
        [weakSelf selectNum];
    };
    cell.countBlock = ^{
        [weakSelf totalCount];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(50);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark - UITextField
- (void)textFieldEditChanged:(UITextField *)textField {
    self.productBarcodeListAPI.productName = textField.text;
    self.productBarcodeSingleListAPI.productName = textField.text;
    self.currentPage = 1;
    [self loadData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - event
-(void)clickedScanBtn {
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        self.searchTf.text = result;
        self.productBarcodeListAPI.productName = result;
        self.productBarcodeSingleListAPI.productName = result;
        self.currentPage = 1;
        [self loadData];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

-(void)clickedGoodsBarcodeBtn:(UIButton *)sender {
    if (sender.selected == YES) {
        return;
    }
    _goodsBarcodeBtn.selected = YES;
    _singleBarcodeBtn.selected = NO;
    _goodsBarcodeBtn.backgroundColor = kBuleColor;
    [_goodsBarcodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _singleBarcodeBtn.backgroundColor = [UIColor whiteColor];
    [_singleBarcodeBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    self.currentPage = 1;
    [self loadData];
}

-(void)clickedSingleBarcodeBtn:(UIButton *)sender {
    if (sender.selected == YES) {
        return;
    }
    _goodsBarcodeBtn.selected = NO;
    _singleBarcodeBtn.selected = YES;
    _goodsBarcodeBtn.backgroundColor = [UIColor whiteColor];
    [_goodsBarcodeBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    _singleBarcodeBtn.backgroundColor = kBuleColor;
    [_singleBarcodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.currentPage = 1;
    [self loadData];
}

- (void)clickStartDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.startDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.endDateLab.text];
        if ([date1 compare:date2] == NSOrderedDescending) {
            [Prompt popPromptViewWithMsg:@"开始日期不能大于截止日期" duration:2];
        }else {
            weakSelf.startDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.productBarcodeListAPI.startTime = selectedDate;
            weakSelf.productBarcodeSingleListAPI.startTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

- (void)clickEndDateBtn:(UIButton *)btn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.endDateLab.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        NSDate *date1 = [self.dateFormatter dateFromString:selectedDate];
        NSDate *date2 = [self.dateFormatter dateFromString:weakSelf.startDateLab.text];
        if ([date1 compare:date2] == NSOrderedAscending) {
            [Prompt popPromptViewWithMsg:@"截止日期不能小于开始日期" duration:2];
        }else {
            weakSelf.endDateLab.text = selectedDate;
            weakSelf.currentPage = 1;
            weakSelf.productBarcodeListAPI.endTime = selectedDate;
            weakSelf.productBarcodeSingleListAPI.endTime = selectedDate;
            [weakSelf loadData];
        }
    };
}

-(void)clickedPrintBtn {
    if (self.selectMarr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请选择需打印的条码" duration:2];
        return;
    }
    
    for (SAPrintLableModel *model in self.selectMarr) {
        if ([model.printNum integerValue] == 0) {
            [Prompt popPromptViewWithMsg:[NSString stringWithFormat:@"%@ 打印标签数量不能为0",model.productName] duration:2];
//            [Prompt popPromptViewWithMsg:@"请选择需要打印的标签" duration:2];
            return;
        }
    }
    
    [self startTime];
    NSInteger printType = [SAValueManger shareInStance].printType;
    if (self.overallSetting.printerSetting.printerStatus == 2 && printType == 2) {
            NSString *type = @"4";
            NSMutableArray *marr = [NSMutableArray array];
            for (SAPrintLableModel *model in self.selectMarr) {
                if (model.barcodeSingle.length == 0 && model.barcode.length == 0) {
                    continue;
                }
                NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
                if (model.barcodeSingle.length > 0) {
                    mdic[@"barcodeSingle"] = model.barcodeSingle;
                    mdic[@"color"] = model.color;
                    mdic[@"size"] = model.size;
                    type = @"5";
                }else {
                    mdic[@"barcode"] = model.barcode;
                    type = @"4";
                }
                mdic[@"printNum"] = model.printNum;
                mdic[@"productCode"] = model.productCode;
                mdic[@"productName"] = model.productName;
                mdic[@"retailPrice"] = model.retailPrice;
                mdic[@"discountPrice"] = model.discountPrice;
                
                mdic[@"component"] = model.component;
                mdic[@"executionStandard"] = model.executionStandard;
                mdic[@"securityCategory"] = model.securityCategory;
                mdic[@"qualityGrade"] = model.qualityGrade;
                mdic[@"washingMode"] = model.washingMode;
                mdic[@"brandName"] = model.brandName;
                mdic[@"ground"] = model.ground;
                mdic[@"dealer"] = model.dealer;
                [marr addObject:mdic];
            }
            
            if (marr.count > 0) {
                NSError *error = nil;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:&error];
                NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                CloudPrint *print = [CloudPrint shareInstance];
                [print PrintWithType:type AndData:jsonString];
            }
    }else {
        if (kIsTestServer == 1) {
            [self CloudPrint];
        }else {
            [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
        }
    }
}

-(void)startTime {
    self.printBtn.userInteractionEnabled = NO;
    [self.printBtn setTitle:@"打印" forState:UIControlStateNormal];
    self.count = 3;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
    } else {
        self.printBtn.userInteractionEnabled = YES;
        [self.printBtn setTitle:@"打印标签" forState:UIControlStateNormal];
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)selectNum {
    self.allSelectBtn.selected = (self.selectMarr.count == self.dataMarr.count);
    if (self.selectMarr.count == 0) {
        self.allSelectBtn.selected = NO;
    }
    if (self.selectMarr.count > 0) {
        self.printBtn.selected = YES;
    }else {
        self.printBtn.selected = NO;
    }
    [self totalCount];
}

-(void)clickedAllSelectBtn {
    [self.view endEditing:YES];
    self.allSelectBtn.selected = !self.allSelectBtn.isSelected;
    [self.selectMarr removeAllObjects];
    for (SAPrintLableModel *model in self.dataMarr) {
        model.isSelect = self.allSelectBtn.isSelected;
        if (model.isSelect == YES) {
            [self.selectMarr addObject:model];
        }
    }
    [self.tableView reloadData];
    [self totalCount];
}

-(void)clickedVipBtn {
//    [self.view endEditing:YES];
//    SASearchSupplierView *searchSupplierView = [SASearchSupplierView shareCornView];
//    UIViewController *vc = nil;
//    [searchSupplierView showView:vc];
//    WeakSelf
////    searchSupplierView.selectBlock = ^(SASupplierModel * _Nonnull supplierModel) {
//        weakSelf.productBarcodeListAPI.providerId = supplierModel.providerId;
//        weakSelf.productBarcodeSingleListAPI.providerId = supplierModel.providerId;
//        [weakSelf loadData];
//    };
    
    [self.view endEditing:YES];
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *isSupplier = [NSString stringWithFormat:@"%@",menuList[7][@"isDelete"]];
    NSString *seeProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"seeProvider"]];
    if ([isSupplier isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
        return;
    }
    if ([seeProvider isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
        return;
    }
    
    SASearchSupplierView *searchSupplierView = [SASearchSupplierView shareCornView];
    UIViewController *vc = nil;
    [searchSupplierView showView:vc];
    WeakSelf
    searchSupplierView.selectBlock = ^(SASupplierModel * _Nonnull supplierModel) {
        if (supplierModel.mobile.length > 0) {
            [weakSelf.vipBtn setTitle:[NSString stringWithFormat:@"%@(%@)",supplierModel.providerName,supplierModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.vipBtn setTitle:supplierModel.providerName forState:UIControlStateNormal];
        }
        
        [weakSelf.vipBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [weakSelf.vipBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.vipBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.vipBtn.titleLabel.bounds.size.width;
        weakSelf.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        weakSelf.cancelBtn.hidden = NO;
        weakSelf.providerId = supplierModel.providerId;
        [weakSelf loadData];
    };
}

-(void)clickedCancelBtn {
    [self.view endEditing:YES];
    self.cancelBtn.hidden = YES;
    [self.vipBtn setTitle:@"请选供货商" forState:UIControlStateNormal];
    [self.vipBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
    CGFloat imageWidth = self.vipBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.vipBtn.titleLabel.bounds.size.width;
    self.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    
    self.productBarcodeListAPI.providerId = @"";
    self.productBarcodeSingleListAPI.providerId = @"";
    [self loadData];
}

-(void)totalCount {
    NSInteger count = 0;
    for (SAPrintLableModel *model in self.selectMarr) {
        count += [model.printNum integerValue];
    }
    self.totalLab.text = [NSString stringWithFormat:@"%zd款,%zd件",self.selectMarr.count,count];
}

-(void)loadData {
    
    self.productBarcodeListAPI.startTime = self.startDateLab.text;
    self.productBarcodeSingleListAPI.startTime = self.startDateLab.text;
    self.productBarcodeListAPI.endTime = self.endDateLab.text;
    self.productBarcodeSingleListAPI.endTime = self.endDateLab.text;
    self.productBarcodeListAPI.providerId = self.providerId;
    self.productBarcodeSingleListAPI.providerId = self.providerId;
    
    if (self.productBarcodeListAPI.productName.length > 0) {
        self.productBarcodeListAPI.startTime = @"";
        self.productBarcodeListAPI.endTime = @"";
        self.productBarcodeListAPI.providerId = @"";
    }
    if (self.productBarcodeSingleListAPI.productName.length > 0) {
        self.productBarcodeSingleListAPI.startTime = @"";
        self.productBarcodeSingleListAPI.endTime = @"";
        self.productBarcodeSingleListAPI.providerId = @"";
    }
    
    self.productBarcodeListAPI.currentPage = self.currentPage;
    self.productBarcodeSingleListAPI.currentPage = self.currentPage;
    if (self.goodsBarcodeBtn.isSelected == YES) {
        [self.productBarcodeListAPI submitForm:POST]; //表单方式提交
    }else {
        [self.productBarcodeSingleListAPI submitForm:POST]; //表单方式提交
    }
}

-(void)CloudPrint {
    SACommoditySpecialFeesModel *labelLayoutAttribute = self.overallSetting.labelLayoutAttribute;
    NSArray *arr = [labelLayoutAttribute.value componentsSeparatedByString:@","];
    if (arr.count < 7) {
        return;
    }
    
    NSString *type = @"4";
    NSMutableArray *marr = [NSMutableArray array];
    int i = 0;
    BOOL isTip = YES;
    for (SAPrintLableModel *model in self.selectMarr) {
        if (model.barcodeSingle.length == 0 && model.barcode.length == 0) {
            continue;
        }
        i++;
        NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
        if (model.barcodeSingle.length > 0) {
            mdic[@"barcodeSingle"] = model.barcodeSingle;
            mdic[@"color"] = model.color;
            mdic[@"size"] = model.size;
            type = @"5";
        }else {
            mdic[@"barcode"] = model.barcode;
            type = @"4";
        }
        mdic[@"printNum"] = model.printNum;
        mdic[@"productCode"] = model.productCode;
        mdic[@"productName"] = model.productName;
        mdic[@"retailPrice"] = model.retailPrice;
        mdic[@"discountPrice"] = model.discountPrice;
        mdic[@"component"] = model.component;
        mdic[@"executionStandard"] = model.executionStandard;
        mdic[@"securityCategory"] = model.securityCategory;
        mdic[@"qualityGrade"] = model.qualityGrade;
        mdic[@"washingMode"] = model.washingMode;
        
        [marr addObject:mdic];
        if (i == 20) { //满20个数据打一次，如果不满20，在下面会推送最后一次
            NSError *error = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:&error];
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
            mdic[@"merchantId"] = [NSString stringWithFormat:@"%zd",[SAValueManger shareInStance].userInfo.merchantId];
            mdic[@"data"] = jsonString;
            mdic[@"type"] = type;
            [marr removeAllObjects];
            i = 0;
            self.isTip = isTip;
            isTip = NO;
            self.cloudPrintPushPrintMsgAPI.coverParameters = mdic;
            [self.cloudPrintPushPrintMsgAPI submitForm:POST];
        }
    }
    
    if (marr.count > 0) {
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:marr options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
        mdic[@"merchantId"] = [NSString stringWithFormat:@"%zd",[SAValueManger shareInStance].userInfo.merchantId];
        mdic[@"data"] = jsonString;
        mdic[@"type"] = type;
        [marr removeAllObjects];
        
        self.isTip = isTip;
        isTip = NO;
        self.cloudPrintPushPrintMsgAPI.coverParameters = mdic;
        [self.cloudPrintPushPrintMsgAPI submitForm:POST];
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@""];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    self.overallSetting = [SAOverallSetting shareInstance];
    
    [self addRightViews:@[self.topView]];
    [self.topView addSubview:self.searchTf];
    [self.topView addSubview:self.scanBtn];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.goodsBarcodeBtn];
    [self.contentView addSubview:self.singleBarcodeBtn];
    
    UIView *supplyView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight + 94, kBaseScreenWidth, 37)];
    supplyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:supplyView];
    
    UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleBtn setImage:[UIImage imageNamed:@"Warehousing_icon_1"] forState:UIControlStateNormal];
    [titleBtn setTitle:@"  供货商" forState:UIControlStateNormal];
    titleBtn.frame = SARectMake(20, 0, 120, 37);
    titleBtn.titleLabel.font = kFont(15);
    [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [supplyView addSubview:titleBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
    rightBtn.frame = SARectMake(0, 0, kBaseScreenWidth - 20, 37);
    rightBtn.titleLabel.font = kFont(15);
    [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [supplyView addSubview:rightBtn];

    [rightBtn setTitle:@"请选择供货商" forState:UIControlStateNormal];
    [rightBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
    self.vipBtn = rightBtn;
    [rightBtn addTarget:self action:@selector(clickedVipBtn) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
    CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
    rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(kBaseScreenWidth - 37, 0, 30, 37);
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [supplyView addSubview:cancelBtn];
    
    [self.view addSubview:self.topContentView];
    [self.topContentView addSubview:self.startLab];
    [self.topContentView addSubview:self.startDateLab];
    [self.topContentView addSubview:self.endLab];
    [self.topContentView addSubview:self.endDateLab];
    [self.topContentView addSubview:self.iconImageV];
    [self.topContentView addSubview:self.startDateBtn];
    [self.topContentView addSubview:self.endDateBtn];
    
    [self.topContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(StatusHeight + 50));
        make.height.mas_equalTo(kScaleNum(44));
        make.right.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(0));
    }];
    
    [self.iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(29, 29));
    }];
    
    [self.startLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.startDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.iconImageV.mas_left).offset(kScaleNum(-68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.endDateLab);
        make.top.mas_equalTo(kScaleNum(2));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.endDateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.iconImageV.mas_right).offset(kScaleNum(68));
        make.top.mas_equalTo(kScaleNum(22));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.startDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.startDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    [self.endDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.endDateLab);
        make.top.bottom.mas_equalTo(0);
    }];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    _startDateLab.text = [dateFormatter stringFromDate:[[NSDate date] leadYear:-1]];
    _endDateLab.text = timeFormatStr;
    
    [self.view addSubview:self.whiteView];
    [self.whiteView addSubview:self.line];
    [self.whiteView addSubview:self.selectLab];
    [self.whiteView addSubview:self.allSelectBtn];
    [self.whiteView addSubview:self.totalLab];
    [self.view addSubview:self.printBtn];
    
    [self.view addSubview:self.tipView];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
    
    self.currentPage = 1;
    self.productBarcodeListAPI.pageSize = 20;
    self.productBarcodeSingleListAPI.pageSize = 20;
    self.productBarcodeListAPI.startTime = _startDateLab.text;
    self.productBarcodeSingleListAPI.startTime = _startDateLab.text;
    self.productBarcodeListAPI.endTime = _endDateLab.text;
    self.productBarcodeSingleListAPI.endTime = _endDateLab.text;
    [self loadData];
}

#pragma mark - lazy
-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:SARectMake(63, 0, 312, 44)];
    }
    return _topView;
}

-(UITextField *)searchTf {
    if (!_searchTf) {
        _searchTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
        _searchTf.placeholder = @"输入商品款号/名称/条码";
        _searchTf.backgroundColor = [UIColor whiteColor];
        _searchTf.layer.cornerRadius = kScaleNum(5);
        _searchTf.layer.masksToBounds = YES;
        _searchTf.delegate = self;
        _searchTf.font = kFont(14);
        _searchTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIView *leftView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 26, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(6, 7, 14, 16)];
        imageV.image = [UIImage imageNamed:@"shop_search"];
        [leftView addSubview:imageV];
        _searchTf.leftView = leftView;
        _searchTf.leftViewMode = UITextFieldViewModeAlways;
        _searchTf.returnKeyType = UIReturnKeyDone;
        [_searchTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTf;
}

-(UIButton *)scanBtn {
    if (!_scanBtn) {
        _scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_scanBtn setImage:[UIImage imageNamed:@"home_scan"] forState:UIControlStateNormal];
        _scanBtn.frame = SARectMake(254, 0, 53, 44);
        [_scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _scanBtn;
}

-(UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - kScaleNum(200))/2, kScaleNum(StatusHeight + 10), kScaleNum(200), kScaleNum(30))];
        _contentView.layer.cornerRadius = kScaleNum(3);
        _contentView.layer.masksToBounds = YES;
    }
    return _contentView;
}

-(UIButton *)goodsBarcodeBtn {
    if (!_goodsBarcodeBtn) {
        _goodsBarcodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _goodsBarcodeBtn.frame = SARectMake(0, 0, 100, 30);
        _goodsBarcodeBtn.backgroundColor = kBuleColor;
        [_goodsBarcodeBtn setTitle:@"商品条码" forState:UIControlStateNormal];
        [_goodsBarcodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _goodsBarcodeBtn.titleLabel.font = kFont(15);
        _goodsBarcodeBtn.selected = YES;
        [_goodsBarcodeBtn addTarget:self action:@selector(clickedGoodsBarcodeBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goodsBarcodeBtn;
}

-(UIButton *)singleBarcodeBtn {
    if (!_singleBarcodeBtn) {
        _singleBarcodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _singleBarcodeBtn.frame = SARectMake(100, 0, 100, 30);
        _singleBarcodeBtn.backgroundColor = [UIColor whiteColor];
        [_singleBarcodeBtn setTitle:@"单品条码" forState:UIControlStateNormal];
        [_singleBarcodeBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        _singleBarcodeBtn.titleLabel.font = kFont(15);
        _singleBarcodeBtn.selected = NO;
        [_singleBarcodeBtn addTarget:self action:@selector(clickedSingleBarcodeBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _singleBarcodeBtn;
}

- (UIView *)topContentView {
    if (!_topContentView) {
        _topContentView = [[UIView alloc] init];
        _topContentView.backgroundColor = [UIColor whiteColor];
    }
    return _topContentView;
}

- (UILabel *)startLab {
    if (!_startLab) {
        _startLab = [[UILabel alloc] init];
        _startLab.textColor = kBlackColor;
        _startLab.font = kFont(15);
        _startLab.text = @"开始";
    }
    return _startLab;
}

- (UILabel *)startDateLab {
    if (!_startDateLab) {
        _startDateLab = [[UILabel alloc] init];
        _startDateLab.textColor = kBlackColor;
        _startDateLab.font = kFont(15);
    }
    return _startDateLab;
}

- (UILabel *)endLab {
    if (!_endLab) {
        _endLab = [[UILabel alloc] init];
        _endLab.textColor = kBlackColor;
        _endLab.font = kFont(15);
        _endLab.text = @"截止";
    }
    return _endLab;
}

- (UILabel *)endDateLab {
    if (!_endDateLab) {
        _endDateLab = [[UILabel alloc] init];
        _endDateLab.textColor = kBlackColor;
        _endDateLab.font = kFont(15);
    }
    return _endDateLab;
}

- (UIImageView *)iconImageV {
    if (!_iconImageV) {
        _iconImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SA_to"]];
    }
    return _iconImageV;
}

- (UIButton *)startDateBtn {
    if (!_startDateBtn) {
        _startDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_startDateBtn addTarget:self action:@selector(clickStartDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _startDateBtn;
}

- (UIButton *)endDateBtn {
    if (!_endDateBtn) {
        _endDateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_endDateBtn addTarget:self action:@selector(clickEndDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endDateBtn;
}

-(NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [NSDateFormatter new];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 88 + 44), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 88 + 44) - kScaleNum(80) - SafeFooterHeight) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SAPrintLableCell class] forCellReuseIdentifier:@"SAPrintLableCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
    return _tableView;
}

-(UIView *)whiteView {
    if (!_whiteView) {
        _whiteView = [[UIView alloc] initWithFrame: CGRectMake(0, kScreenHeight - kScaleNum(80) - SafeFooterHeight, kScreenWidth, kScaleNum(40))];
        _whiteView.backgroundColor = [UIColor whiteColor];
    }
    return _whiteView;
}

-(UIButton *)printBtn {
    if (!_printBtn) {
        _printBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _printBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(40) - SafeFooterHeight, kScreenWidth, kScaleNum(40) + SafeFooterHeight);
        _printBtn.backgroundColor = kBuleColor;
        [_printBtn setTitle:@"打印标签" forState:UIControlStateNormal];
        [_printBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _printBtn.titleLabel.font = kFont(18);
        _printBtn.selected = YES;
        [_printBtn addTarget:self action:@selector(clickedPrintBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _printBtn;
}

-(SAProductBarcodeListAPI *)productBarcodeListAPI {
    if (!_productBarcodeListAPI) {
        _productBarcodeListAPI = [SAProductBarcodeListAPI apiWithDelegate:self];
    }
    return _productBarcodeListAPI;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 88 + 44), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 88 + 44))];
        _tipView.backgroundColor = kLineColor;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 150, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(NSMutableArray<SAPrintLableModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(NSMutableArray<SAPrintLableModel *> *)selectMarr {
    if (!_selectMarr) {
        _selectMarr = [NSMutableArray array];
    }
    return _selectMarr;
}

-(UIButton *)allSelectBtn {
    if (!_allSelectBtn) {
        _allSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allSelectBtn.frame = SARectMake(0, 0, 62, 40);
        [_allSelectBtn setImage:[UIImage imageNamed:@"print_check_n"] forState:UIControlStateNormal];
        [_allSelectBtn setImage:[UIImage imageNamed:@"print_check_s"] forState:UIControlStateSelected];
        [_allSelectBtn addTarget:self action:@selector(clickedAllSelectBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allSelectBtn;
}

-(UILabel *)selectLab {
    if (!_selectLab) {
        _selectLab = [[UILabel alloc] initWithFrame:SARectMake(62, 0, 50, 40)];
        _selectLab.text = @"全选";
        _selectLab.textColor = kBlackColor;
        _selectLab.font = kFont(15);
    }
    return _selectLab;
}

-(UILabel *)totalLab {
    if (!_totalLab) {
        _totalLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 220, 0, 200, 40)];
        _totalLab.text = @"共0款,0件";
        _totalLab.textAlignment = NSTextAlignmentRight;
        _totalLab.textColor = kBlackColor;
        _totalLab.font = kFont(15);
    }
    return _totalLab;
}

-(UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
        _line.backgroundColor = kBgColor;
    }
    return _line;
}

-(SAProductBarcodeSingleListAPI *)productBarcodeSingleListAPI {
    if (!_productBarcodeSingleListAPI) {
        _productBarcodeSingleListAPI = [SAProductBarcodeSingleListAPI apiWithDelegate:self];
    }
    return _productBarcodeSingleListAPI;
}

-(SACloudPrintPushPrintMsgAPI *)cloudPrintPushPrintMsgAPI {
    if (!_cloudPrintPushPrintMsgAPI) {
        _cloudPrintPushPrintMsgAPI = [SACloudPrintPushPrintMsgAPI apiWithDelegate:self];
    }
    return _cloudPrintPushPrintMsgAPI;
}

@end
